import json
import time
import os
import re
import conf
from douyin_download.browser_mian import BuildQueryRequest
from utils.download_tool import download_video
from icecream import ic
class VideoInfoModel:

    def __init__(self,data:str):
        '''
        初始化模型实例
        :param data:接口返回的json数据字符串
        '''
        self.data = data
        self.current_time=time.strftime("%Y-%m-%d", time.localtime())
        self.now_timestamp=int(time.time())
        #josn变字典,准备模型数据
        try:
            self.data_dict = json.loads(self.data)
        except Exception as e:
            print(e)
        self.video_base_data_list=[]
    def add_video_info_data(self,size:int=10) -> list:

        '''
        默认获取接口返回的前10条消息
        :return:
        '''
        video_count=0
        for i in range(size):
            try:
                # 置顶标识，0为否，1为是，方便过滤
                self.is_top = self.data_dict['aweme_list'][i]['is_top']
                self.nick_name = self.data_dict['aweme_list'][i]['author']['nickname']
                self.aweme_id = self.data_dict['aweme_list'][i]['aweme_id']
                self.desc = self.data_dict['aweme_list'][i]['desc']
                self.create_time = self.data_dict['aweme_list'][i]['create_time']
                self.music_play_url = self.data_dict['aweme_list'][i]['music']['play_url']['uri']
                self.video_url_list = self.data_dict['aweme_list'][i]['video']['play_addr']['url_list']
                self.cover_url_list = self.data_dict['aweme_list'][i]['video']['cover']['url_list']
                self.video_url = self.data_dict['aweme_list'][i]['video']['cover']['uri']
            except Exception as e:
                print(e)

            if self.is_top == 1:
                continue
            else:
                #写入模型数据
                self.video_base_model = {
                    "nick_name": self.nick_name,
                    "aweme_list":[
                        {
                            "aweme_id": self.aweme_id,
                            "desc": self.desc,
                            "create_time": self.create_time,
                            "is_top": self.is_top,
                            "music": {
                                "play_url": self.music_play_url
                            },
                            "video": {
                                "play_addr": {
                                    "url_list": self.video_url_list
                                },
                                "cover": {
                                    "uri": self.video_url,
                                    "url_list": self.cover_url_list
                                }
                            }
                        }
                        ]
                    }
                self.video_base_data_list.append(self.video_base_model)
                video_count+=1
        print(f'共获取到{video_count}条视频信息')
        return self.video_base_data_list

    def get_available_videos_by_timediffence(self,auto_down:bool=True,time_diffence:int=conf.query_video_time_diffence) -> list:
        '''

        通过发布时间差获取视频信息
        :param time_diffence: 单位s
        :return:list
        '''
        data=self.add_video_info_data()
        available_video_list=[]
        available_video_count=0
        for video_info in data:
            if self.now_timestamp - int(video_info['aweme_list'][0]['create_time'])<time_diffence:
                available_video_list.append(video_info)
                available_video_count+=1
            else:
                continue
        print(f'共获取到{available_video_count}条符合时间差{time_diffence}s的视频信息')
        #输出记录，后续用log形式体现
        video_log=''
        file_name=f'{self.current_time}.txt'
        for video_boj in available_video_list:

            with open(f'{os.path.join(conf.log_dir,file_name)}','a',encoding='utf-8') as f:
                f.write(f'作者昵称:{video_boj["nick_name"]};视频id:{video_boj["aweme_list"][0]["aweme_id"]};视频描述:{video_boj["aweme_list"][0]["desc"]};视频发布时间:{video_boj["aweme_list"][0]["create_time"]}\n')


            '''
            自动下载逻辑，后续可以添加id判重，如果文件夹里面已有，则不下载，后续可以通过log文件内记录的id来实现。
            重复下载也不会新增文件，文件名是静态数据，只会覆盖。但可以做已下载的记录
            '''
            if auto_down == True:
                url,desc=self.get_available_video_play_url_and_desc(video_boj)
                download_video(url,desc)
            else:
                print('未开启自动下载')
                pass

        return available_video_list


    def get_available_video_play_url_and_desc(self,data):

        '''
        获取视频播放地址
        :param data:可以处理单个视频，也可以处理多个视频数组
        :return:
        '''
        if isinstance(data,list):
            if data == []:
                return '未获取到可用的视频信息'
            self.available_video_url=[]
            self.available_video_url_count=0

            for video in data:
                #视频播放地址是一个列表，其实那一条就够了
                self.video_url = video['aweme_list'][0]['video']['play_addr']['url_list'][0]
                self.available_video_url.append(self.video_url)
                self.available_video_url_count+=1
            print(f'共获取到{self.available_video_url_count}条可用的视频播放地址')
            return self.available_video_url
        if isinstance(data,dict):
            self.video_url = data['aweme_list'][0]['video']['play_addr']['url_list'][0]
            self.video_desc=data['aweme_list'][0]['desc']
            self.video_desc=re.sub(r'\s+','',self.video_desc)
            self.video_id=data['aweme_list'][0]['aweme_id']
            #组装文件名称
            self.file_name=f'{self.video_id}_{self.video_desc}.mp4'
            return self.video_url,self.file_name

    def get_video_cover_url(self,data:list):
        for video_obj in data:
            self.cover_url_list = video_obj['aweme_list'][0]['video']['cover']['url_list']
        return self.cover_url_list

    def get_music_play_url(self,data:list):
        for video_obj in data:
            self.music_play_url = video_obj['aweme_list'][0]['music']['play_url']['uri']
        return self.music_play_url

    def get_video_desc(self,data:list):
        for video_obj in data:
            self.desc = video_obj['aweme_list'][0]['desc']
        return self.desc

    def get_video_create_time(self,data:list):
        for video_obj in data:
            self.create_time = video_obj['aweme_list'][0]['create_time']
        return self.create_time

    def get_video_aweme_id(self,data:list):
        for video_obj in data:
            self.aweme_id = video_obj['aweme_list'][0]['aweme_id']
        return self.aweme_id

    def get_video_nick_name(self,data:list):
        for video_obj in data:
            self.nick_name = video_obj['aweme_list'][0]['nickname']
        return self.nick_name

    def get_video_info_by_aweme_id(self,aweme_id:str):
        '''
        通过aweme_id获取视频信息
        :param aweme_id:
        :return:
        '''
        for video_obj in self.add_video_info_data():
            if video_obj['aweme_list'][0]['aweme_id'] == aweme_id:
                return video_obj
            else:
                continue


if __name__ == '__main__':
    video_base_data_list = VideoInfoModel(BuildQueryRequest().get_video_info()).get_available_videos_by_timediffence()
    ic(video_base_data_list)